package com.lianzhihui.romeex.ui.wallet;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.zxing.client.android.Intents;
import com.lianzhihui.romeex.R;
import com.lianzhihui.romeex.bean.SaveAddressInfo;
import com.lianzhihui.romeex.bean.WalletMainBean;
import com.lianzhihui.romeex.bean.ZZConfigBean;
import com.lianzhihui.romeex.bean.ZZPostBean;
import com.lianzhihui.romeex.config.AppConstants;
import com.lianzhihui.romeex.config.MessageEvent;
import com.lianzhihui.romeex.inter.DialogListener;
import com.lianzhihui.romeex.inter.SetListener;
import com.lianzhihui.romeex.mvp.presenter.ZZConfigPresenter;
import com.lianzhihui.romeex.mvp.presenter.ZZPresenter;
import com.lianzhihui.romeex.mvp.view.ZZConfigView;
import com.lianzhihui.romeex.mvp.view.ZZView;
import com.lianzhihui.romeex.ui.base.BaseFragment;
import com.lianzhihui.romeex.ui.me.AddressActivity;
import com.lianzhihui.romeex.ui.qrcode.ScanActivity;
import com.lianzhihui.romeex.utils.CoinUtils;
import com.lianzhihui.romeex.utils.LogUtil;
import com.lianzhihui.romeex.utils.MathUtil;
import com.lianzhihui.romeex.utils.NoDoubleClickUtils;
import com.lianzhihui.romeex.utils.NumberUtils;
import com.lianzhihui.romeex.utils.QrUtils.QRUtils;
import com.lianzhihui.romeex.utils.TextUtil;
import com.lianzhihui.romeex.utils.UiUtils;
import com.lianzhihui.romeex.widget.dialog.ZZFailDialog;
import com.lianzhihui.romeex.widget.dialog.ZZSucDialog;
import com.lianzhihui.romeex.widget.dialog.ZhuanzhangDialog;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.OnClick;

import static android.app.Activity.RESULT_OK;

/**
 * Description: 跨链转账
 * Author: RAMON
 * CreateDate: 11/15/20 10:39 AM
 * UpdateUser:
 * UpdateDate:
 * UpdateRemark:
 * Version:
 */
public class ZhuanZhangFragment extends BaseFragment implements ZZConfigView, ZZView {

    @BindView(R.id.tv_target)
    TextView tv_target;
    @BindView(R.id.iv_scan)
    ImageView iv_scan;
    @BindView(R.id.iv_address_book)
    ImageView iv_address_book;
    @BindView(R.id.et_sum)
    EditText et_sum;
    @BindView(R.id.tv_unit)
    TextView tv_unit;
    @BindView(R.id.tv_suoha)
    TextView tv_suoha;
    @BindView(R.id.tv_canuse)
    TextView tv_canuse;
    @BindView(R.id.tv_service)
    TextView tv_service;
    @BindView(R.id.tv_unit2)
    TextView tv_unit2;
    @BindView(R.id.tv_cross_warnning)
    TextView tv_cross_warnning;
    @BindView(R.id.et_remark)
    EditText et_remark;
    @BindView(R.id.bt_submit)
    Button bt_submit;

    WalletMainBean.CoinBean coin;
    ZZConfigBean.ConfigBean config;
    ZZConfigPresenter presenter;
    ZZPresenter bizPresenter;
    ZZConfigBean bean;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_zhuanzhang_layout;
    }

    @Override
    protected void initView() {

        coin = ((CrossChainActivity) getActivity()).coin;
        if (coin == null) {
            coin = CoinUtils.getDefCoin();
        }

        UiUtils.setEditText8(et_sum, new SetListener() {
            @Override
            public void getInput(double content) {
                fee();
            }
        });
        tv_unit.setText(coin.getCoinNameAlias());

        presenter = new ZZConfigPresenter(activity, this);
        bizPresenter = new ZZPresenter(activity, this);

    }

    private void getConfig(){
        showLoading("");
//        LogUtil.error("ramon","获取配置");
        presenter.getConfig(coin.getCoinName(), coin.getCoinNameCobo(), 2);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onCoinSuccess(ZZConfigBean bean) {
        dismissLoading();
//        LogUtil.error("ramon", "config: " + bean.getConfig().toString());
        //todo 适配转账数据
        this.bean = bean;
        config = bean.getConfig();
        tv_canuse.setText(NumberUtils.big8(bean.getBalance()));
        fee();
        setWarning();
    }

    public void setWarning(){
        //文案
        String string = getString(R.string.zhuanzhang_warning_p1_1)+
                coin.getCoinNameAlias()
                +getString(R.string.zhuanzhang_warning_p1_2)+
                config.getMinMoney()+ " " +coin.getCoinNameAlias() +
                getString(R.string.zhuanzhang_warning_p2);
        tv_cross_warnning.setText(string);
    }

    public void fee() {
        String fee = "0";
        if (config.getValue().equals("fixed")) {
            //固定 费用
            fee = NumberUtils.big8(config.getFixed());
        }

        if (config.getValue().equals("rate")) {
            String sumStr = et_sum.getText().toString();
            double sum = 0D;
            if (TextUtils.isEmpty(sumStr)) {
                sum = 0D;
            } else {
                sum = Double.parseDouble(et_sum.getText().toString());
            }
            //计算费率
            double res = MathUtil.multiply(sum, config.getRate());
            fee = NumberUtils.big8(res);
        }
        tv_service.setText(fee);
        tv_unit2.setText(config.getCoinName());
    }

    @Override
    public void onCoinFail(Object obj) {
        toast("获取数据失败");
        finish();
    }

    @Override
    public void setFailure() {

    }

    @Override
    public void onZZSuccess(String transactionHashcode) {
        dismissLoading();
        EventBus.getDefault().post(new MessageEvent(AppConstants.Event.REFRESHER_ASSETS, true));
        ZZSucDialog sucDialog = new ZZSucDialog(activity);
        double sum = Double.parseDouble(et_sum.getText().toString());
        sucDialog.setSum(sum, coin.getCoinNameAlias());
        sucDialog.setListener(new DialogListener() {
            @Override
            public void onPassed() {
                //跳转详情
                Intent intent = new Intent(activity, TradeRecordDetailsActivity.class);
                intent.putExtra(AppConstants.RECORD_DETAILS_KEY, transactionHashcode);
                intent.putExtra("tradeType", "1");
                intent.putExtra("coinName", coin.getCoinName());
                startActivity(intent);
            }

            @Override
            public void onFail() {

            }
        });
        sucDialog.show();
    }

    @Override
    public void onZZFail() {
        dismissLoading();
        ZZFailDialog failDialog = new ZZFailDialog(activity);
        double sum = Double.parseDouble(et_sum.getText().toString());
        failDialog.setSum(sum, coin.getCoinNameAlias());
        failDialog.show();
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != RESULT_OK) {
            return;
        }
        if (requestCode == AppConstants.Intent.ADDRESS) {
            //加载地址
            SaveAddressInfo.Address addressBean = (SaveAddressInfo.Address) data.getSerializableExtra("bean");
            tv_target.setText(addressBean.getAddress());
        }
        // 扫描二维码/条码回传
        //todo 二维码 导入私钥回调
        if (requestCode == AppConstants.Intent.SCAN) {
            if (data != null) {
                //返回的文本内容
                String content = data.getStringExtra(Intents.Scan.RESULT);
                LogUtil.error("ramon", "result: " + content);
                if (TextUtils.isEmpty(content)) {
                    toast("无效二维码");
                    return;
                }
//                String scanResult = QRUtils.getContentString(content, 5);
//                String[] split = scanResult.split("_");  // split[0] 数量  split[1] 钱包地址 split[2] 币种
//                String sum = split[0];
//                String tagAddress = split[1];
//                String coinType = split[2];
//                if (!coin.getCoinNameAlias().equals(coinType)) {
//                    toast("不可转账币种");
//                    return;
//                }
                tv_target.setText(content);
//                switch (QRUtils.scanType(content)) {
//                    case 1:
//                        //转账
//                        String scanResult = QRUtils.getContentString(content, 1);
//                        String[] split = scanResult.split("_");  // split[0] 数量  split[1] 钱包地址 split[2] 币种
//                        String sum = split[0];
//                        String address = split[1];
//                        coin = QRUtils.getCoinByAlias(split[2]);
//                        //设置数据
//                        et_sum.setText(sum);
//                        tv_target.setText(StringTool.addHead(address));
//                        break;
//                    case 2:
//                        //地址
//                        String tagAddress = QRUtils.getContentString(content, 2);
//                        tv_target.setText(StringTool.addHead(tagAddress));
//                        break;
//                    case 5:
//
//                        String scanResult = QRUtils.getContentString(content, 5);
//                        String[] split = scanResult.split("_");  // split[0] 数量  split[1] 钱包地址 split[2] 币种
//                        String sum = split[0];
//                        String tagAddress = split[1];
//                        String coinType = split[2];
//                        if (!coin.getCoinNameAlias().equals(coinType)) {
//                            toast("不可转账币种");
//                            return;
//                        }
//                        tv_target.setText(tagAddress);
//
//                    default:
//                        break;
//                }
            }
        }
    }

    @OnClick({R.id.bt_submit, R.id.iv_scan, R.id.iv_address_book, R.id.tv_suoha})
    public void onClick(View view) {
        if (NoDoubleClickUtils.isDoubleClick()) {
            switch (view.getId()) {

                case R.id.bt_submit:

                    String tagAddress = tv_target.getText().toString();
//                tagAddress = StringTool.subHead(tagAddress);
                    if (TextUtils.isEmpty(tagAddress)) {
                        toast(getString(R.string.address_not_null));
                        return;
                    }
                    String sumStr = et_sum.getText().toString();
                    if(TextUtils.isEmpty(sumStr)){
                        toast("请输入金额");
                        return;
                    }
                    double sum = Double.parseDouble(sumStr);

                    double feesum = Double.parseDouble(tv_service.getText().toString());
                    double allsum = sum + feesum;
                    if (sum <= 0) {
                        toast("请输入正确的数量");
                        return;
                    }
                    if (allsum > bean.getBalance()) {
                        toast("转账金额超出可用余额");
                        return;
                    }
                    ZhuanzhangDialog dialog = new ZhuanzhangDialog(activity);
                    dialog.setSum(sum, "");
                    String finalTagAddress = tagAddress;
                    double finalSum = sum;
                    dialog.setListener(new DialogListener() {
                        @Override
                        public void onPassed() {
                            LogUtil.error("ramon", "success");
                            //转账 逻辑
                            ZZPostBean post = new ZZPostBean();
                            post.setTargetUserAddress(finalTagAddress);
                            post.setCoinName(coin.getCoinName());
                            post.setCoinNameCobo(coin.getCoinNameCobo());
                            post.setRemark(et_remark.getText().toString());
                            post.setAmount(finalSum);
                            post.setChainType(2);
                            dialog.dismiss();
                            showLoading("");
                            bizPresenter.zzBiz(post);
                        }

                        @Override
                        public void onFail() {
                            toast("安全码错误");
                        }
                    });
                    dialog.show();
                    break;
                case R.id.iv_scan:
                    startActivityForResult(new Intent(activity, ScanActivity.class), AppConstants.Intent.SCAN);
                    break;
                case R.id.iv_address_book:
                    Intent intent = new Intent(activity, AddressActivity.class);
                    intent.putExtra("isSelect", 0);
                    startActivityForResult(intent, AppConstants.Intent.ADDRESS);
                    break;
                case R.id.tv_suoha:
                    et_sum.setText(NumberUtils.big8(bean.getBalance()));
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    protected void onFragmentFirstVisible() {
        super.onFragmentFirstVisible();
        getConfig();
    }
}
